import React, { useState, useEffect, useRef } from 'react'
import axios from 'axios'
import './VerificationCode.css'

const VerificationCode = ({ 
  type = 'phone', // 'phone' 或 'email'
  target, // 手机号或邮箱
  purpose = 'register', // 用途: 'register', 'login', 'reset-password'
  onCodeSent, // 验证码发送成功回调
  onError, // 错误回调
  disabled = false,
  placeholder = "请输入验证码",
  value = "",
  onChange,
  required = false,
  maxLength = 6
}) => {
  const [countdown, setCountdown] = useState(0)
  const [sending, setSending] = useState(false)
  const timerRef = useRef(null)

  // 验证目标格式
  const validateTarget = () => {
    if (type === 'phone') {
      return /^1[3-9]\d{9}$/.test(target)
    } else if (type === 'email') {
      return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(target)
    }
    return false
  }

  // 发送验证码
  const sendVerificationCode = async () => {
    if (!target || !target.trim()) {
      onError && onError(`请先输入${type === 'phone' ? '手机号' : '邮箱'}`)
      return
    }

    if (!validateTarget()) {
      onError && onError(`请输入有效的${type === 'phone' ? '手机号' : '邮箱'}`)
      return
    }

    try {
      setSending(true)
      
      const response = await axios.post('http://localhost:3001/lxt/send-verification-code', {
        type,
        target: target.trim(),
        purpose
      })

      if (response.data.code === 200) {
        setCountdown(60)
        onCodeSent && onCodeSent(response.data.msg || '验证码已发送')
      } else {
        throw new Error(response.data.msg || '发送失败')
      }
    } catch (error) {
      console.error('发送验证码失败:', error)
      
      let errorMessage = '发送验证码失败，请稍后重试'
      if (error.response && error.response.data && error.response.data.msg) {
        errorMessage = error.response.data.msg
      }
      
      onError && onError(errorMessage)
    } finally {
      setSending(false)
    }
  }

  // 倒计时逻辑
  useEffect(() => {
    if (countdown > 0) {
      timerRef.current = setTimeout(() => {
        setCountdown(countdown - 1)
      }, 1000)
    }

    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current)
      }
    }
  }, [countdown])

  // 组件卸载时清理定时器
  useEffect(() => {
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current)
      }
    }
  }, [])

  return (
    <div className="verification-code-wrapper">
      <div className="verification-input-group">
        <input
          type="text"
          value={value}
          onChange={onChange}
          placeholder={placeholder}
          maxLength={maxLength}
          required={required}
          disabled={disabled}
          className="verification-code-input"
        />
        <button
          type="button"
          className="verification-code-btn"
          onClick={sendVerificationCode}
          disabled={countdown > 0 || sending || disabled}
        >
          {sending ? '发送中...' : (countdown > 0 ? `${countdown}秒后重发` : "获取验证码")}
        </button>
      </div>
    </div>
  )
}

export default VerificationCode 